package com.guiji.text2video.fastvideo.service.Impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guiji.text2video.common.core.utils.DateUtils;
import com.guiji.text2video.fastvideo.domain.vo.*;
import com.guiji.text2video.fastvideo.mapper.Text2videoComposeTaskMapper;
import com.guiji.text2video.fastvideo.mapper.Text2videoTtsTaskMapper;
import com.guiji.text2video.fastvideo.service.IAsyncTTSService;
import com.guiji.text2video.fastvideo.service.INLPService;
import com.guiji.text2video.fastvideo.service.IText2videoJobService;
import com.guiji.text2video.fastvideo.service.IText2videoNlpTaskService;
import com.guiji.text2video.fastvideo.utils.DigitalHuman;
import com.guiji.text2video.fastvideo.utils.Enums;
import com.guiji.text2video.fastvideo.utils.GeneratID;
import com.guiji.text2video.fastvideo.utils.ObjectUtils;
import com.guiji.text2video.system.api.RemoteNLPService;
import okhttp3.*;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RefreshScope
@EnableAsync
@Service
public class GuijiNLPServiceImpl implements INLPService {
    private static final Logger logger = LoggerFactory.getLogger(GuijiNLPServiceImpl.class);

    @Value("${guiji.nlp.charset}")
    private String charset;
    @Value("${file-cache.nlu-new-url}")
    private String NLU_NEW_URL;
    @Value("${async.executor.thread.name.TTSPrefix}")
    private String nameTTSPrefix;
    @Value("${async.executor.thread.name.VideoComposePrefix}")
    private String nameVideoComposePrefix;

    @Value("${file-cache.nlp-domain}")
    private int nlpDomain;
    @Value("${file-cache.nlp-model}")
    private int nlpModel;
    @Value("${file-cache.nlp-threshold}")
    private float nlpThreshold;
    @Value("${file-cache.nlp-words-num}")
    private int nlpWordsNum;
    @Value("${file-cache.nlp-backup}")
    private String nlpBackup;

    @Value("${file-cache.rate}")
    private int speechRate;
    @Value("${file-cache.tts-url}")
    private String ttsURLAlbaba;
    @Value("${file-cache.speaker}")
    private String speaker;

    @Value("${file-cache.tts-url-guiji}")
    private String ttsURLGu;
    @Value("${file-cache.speaker-guiji}")
    private String speakerGu;

    @Value("${file-cache.tts-microsoft}")
    private String ttsURLMicrosoft;
    @Value("${file-cache.speaker-microsoft}")
    private String speakerMicrosoft;

    @Value("${file-cache.tts-zh-microsoft}")
    private String ttsZhURLMicrosoft;
    @Value("${file-cache.speaker-zh-microsoft}")
    private String speakerZhMicrosoft;

    @Value("${file-cache.tts-sougou}")
    private String ttsURLSouGou;
    @Value("${file-cache.speaker-sougou}")
    private String speakerSouGou;

    @Value("${file-cache.tts-sougou-english}")
    private String ttsURLSouEng;
    @Value("${file-cache.speaker-sougou-english}")
    private String speakerSouEng;

    @Resource(name = "asyncEnglishAlibabaTTSServiceImpl")
    private IAsyncTTSService englishTts;

    @Resource(name = "asyncAlibabaTTSServiceImpl")
    private IAsyncTTSService chineseTts;

    @Resource(name = "asyncGuijiTTSServiceImpl")
    private IAsyncTTSService guijiTTS;

    @Resource
    IText2videoNlpTaskService NlpTaskService;
    @Autowired
    private VideoComposeService videoComposeService;

    @Autowired
    private IText2videoJobService text2videoJobService;

    @Autowired(required = false)
    private Text2videoTtsTaskMapper text2videoTtsTaskMapper;

    @Autowired(required = false)
    private RemoteNLPService remoteNLPService;

    @Autowired(required = false)
    private Text2videoComposeTaskMapper composeTaskMapper;

    @Override
    @Async("asyncNLPServiceExecutor")
    public void executeNLPAsync(Text2videoJob job) throws InterruptedException {

        //新闻文本,单窗口执行
        if (ObjectUtils.isNotEmpty(job.getTtsType()) && (job.getTtsType().equals("-3") || job.getTtsType().equals("-1")) && job.getContent().contains("==")) {
            job.setBackup4(job.getContent().split("==")[1]);
            job.setContent(job.getContent().split("==")[0]);
        }
        if (ObjectUtil.isNotEmpty(job.getBackup4())) {
            job.setBackup4(job.getBackup4().replace(" ", ""));
        }

        // 1，过滤特殊字符
        filterSpecialCharacter(job);

        //2，调用NLP
        ArrayList<Sentence> sentenceList = getGuiJiNLPResponse(job);
        if (CollectionUtils.isEmpty(sentenceList)) {
            return;//终止当前线程
        }
        //3，触发异步,TTS任务
        splitSectionTTS(sentenceList, job);
        //4，触发异步,合成任务
        startComposeVideo(sentenceList, job);
    }

    /**
     * @descp: 过滤特殊字符串
     * @param:
     * @Author: scl
     * @Date: 2021/7/8 14:39
     */
    private void filterSpecialCharacter(Text2videoJob tpt) {
        String content = tpt.getContent();
        // 1.还原被转义的HTML特殊字符
        content = HtmlUtil.unescape(content);
        // 2.清除所有HTML标签，但是保留标签内的内容
        content = HtmlUtil.cleanHtmlTag(content);

        // 3.处理一些特殊字符
        char[] blackCharList = new char[]{CharUtil.CR, '>', '<', 65279, 12288};
        content = StrUtil.removeAll(content, blackCharList);

        // 4.处理一些特殊字符串
        String[] blackStrList = new String[]{"</SPAN", "<SPAN", "<br", "</p", "<p", "<img", "<a", "/N"};
        for (String blackStr : blackStrList) {
            content = StrUtil.replaceIgnoreCase(content, blackStr, new String());
        }
        tpt.setContent(content);
    }


    /**
     * @descp: 切分段落-分句，提交不同的tts线程池
     * @param:
     * @Author: scl
     * @Date: 2021/9/3 10:29
     */
    private void splitSectionTTS(ArrayList<Sentence> sentenceList, Text2videoJob job) {
        int countSent = 0;
        for (int i = 0; i < sentenceList.size(); i++) {
            countSent = countSent + sentenceList.get(i).getSentences().size();
        }
        job.setSentenceSize(Integer.toString(countSent));
        job.setSectionSize(Integer.toString(sentenceList.size()));
        job.setContentSize(job.getContent().length());
        text2videoJobService.updateText2videoJob(job);
        if (ObjectUtils.isEmpty(job.getTtsSpeaker())) {
            job.setTtsSpeaker(speaker);
        }
        if (ObjectUtils.isEmpty(job.getTtsRate())) {
            job.setTtsRate(speechRate);
        }


        /**
         * @descp: 任务类型分开，发音人要分开。
         * TTS有三类线程池，speaker使用哪个url,哪个线程池
         * @param: splitSectionTTS
         * @Author: scl
         * @Date: 2021/10/14 10:24
         */
        submitNewsTTS(sentenceList, job);
    }

    /**
     * @descp: 四大名著调用TTS
     * @param:
     * @Author: scl
     * @Date: 2021/10/14 11:25
     */
    private void submitNewsTTS(ArrayList<Sentence> sentenceList, Text2videoJob job) {
        //微软tts
        String speaker = job.getTtsSpeaker();
        if (speaker.contains("WWW")) {
            speaker = speaker.split("WWW")[0];
        }
        if (speakerSouGou.contains(speaker)) {
            //中文线程池-腾讯 TTS
            poolTTSExec(chineseTts, sentenceList, job, ttsURLSouGou);
        } else if (speakerGu.contains(speaker)) {
            //单独线程池-自研-tts
            poolTTSExec(guijiTTS, sentenceList, job, ttsURLGu);
        } else if (speakerMicrosoft.contains(speaker)) {
            //中文线程池-微软英文
            poolTTSExec(chineseTts, sentenceList, job, ttsURLMicrosoft);
        } else if (speakerZhMicrosoft.contains(speaker)) {
            //中文线程池-微软中文
            poolTTSExec(chineseTts, sentenceList, job, ttsZhURLMicrosoft);
        } else if (speakerSouEng.contains(job.getTtsSpeaker())) {
            //英文线程池-搜狗英文-废弃状态
            poolTTSExec(englishTts, sentenceList, job, ttsURLSouEng);
        } else {
            //中文线程池-阿里-中英文
            poolTTSExec(chineseTts, sentenceList, job, ttsURLAlbaba);
        }
    }

    private void poolTTSExec(IAsyncTTSService poolTts, ArrayList<Sentence> sentenceList, Text2videoJob job, String finalRealTTSUrl) {
        sentenceList.forEach(ele -> {
            ele.getSentences().forEach(sent -> {
                poolTts.executeTTSAsync(sent, job, finalRealTTSUrl);
            });
        });
    }


    /**
     * nlp服务三部分
     * 1，初始化任务。
     * 2，请求NLP服务数据。
     * 3，筛选，整理结果。
     *
     * @param job job信息
     * @return 任务对象
     * @throws Exception
     */
    private ArrayList<Sentence> getGuiJiNLPResponse(Text2videoJob job) {
        //1，初始化任务
        Text2videoNlpTask nlpTask = initText2videoNlpTask(job);
        //2，请求NLP服务数据
        JSONObject jsonObject = getGuijiNLPService(job, nlpTask);
        //3，筛选，整理结果。新闻生成
        boolean isNewsJob = (ObjectUtils.isNotEmpty(job.getTtsType()) && (job.getTtsType().equals("-1") || job.getTtsType().equals("-3")));
        if (isNewsJob) {
            return reComputeResultNews(jsonObject, job);
        }
        return reComputeResult(jsonObject);

    }

    /**
     * @descp: 重新计算NLP的结果（新闻）
     * @param:
     * @Author: scl
     * @Date: 2021/9/3 10:41
     */
    private ArrayList<Sentence> reComputeResultNews(JSONObject jsonObject, Text2videoJob job) {
        ArrayList<Sentence> sentences = new ArrayList<>();
        JSONArray data = jsonObject.getJSONArray("data");
        List<NlpSentence> NlpSentenceList = JSONUtil.toList(JSONUtil.parseArray(data.toJSONString()), NlpSentence.class);

        if ("358".equals(job.getBackup5())) {
            Sentence sentenceTile = new Sentence();
            sentenceTile.setIndex(1);
            //"picGenArgs":{"Layout":"right"}

            PicGenArgs picGenArgs = new PicGenArgs();
            picGenArgs.setLayout("right");
            sentenceTile.setPicGenArgs(picGenArgs);

            sentenceTile.setSentences(ListUtil.toList(jsonObject.getString("title")));
            //标题图片
            if (ObjectUtils.isEmpty(job.getBackup4())) {
                logger.info("没有默认图片:{}", JSONUtil.parseObj(job).toString());
                sentenceTile.setFirstImgId(ListUtil.toList("http://172.16.160.54/text2video/news/default-news-picture.jpg"));
            } else {
                sentenceTile.setFirstImgId(ListUtil.toList(job.getBackup4().replace("\"", "").split(",")[0]));
            }
            sentenceTile.setISTitle(Boolean.TRUE);
            sentences.add(sentenceTile);


            for (int i = 0; i < NlpSentenceList.size(); i++) {
                //执行段落分句。
                Sentence sentence = new Sentence();
                sentence.setIndex(i + 2);
                //分句,防止空指针
                if (ObjectUtils.isNotEmpty(NlpSentenceList.get(i).getSentList())) {
                    sentence.setSentences(NlpSentenceList.get(i).getSentList());
                } else {
                    sentence.setSentences(ListUtil.empty());
                }
                //英文使用段落，请求
                if (job.getTtsType().equals("-3")) {
                    sentence.setSentences(ListUtil.toList(NlpSentenceList.get(i).getSent()));
                }

                sentence.setISTitle(Boolean.FALSE);
                //内容图片
                if (ObjectUtils.isEmpty(job.getBackup4())) {
                    sentence.setImages(ListUtil.toList("http://172.16.160.54/text2video/news/default-news-picture.jpg"));
                } else {
                    sentence.setImages(ListUtil.toList(job.getBackup4().replace("\"", "").split(",")));
                }
                sentences.add(sentence);
            }
            return sentences;
        }

        if ("360".equals(job.getBackup5())) {
            for (int i = 0; i < NlpSentenceList.size(); i++) {
                //执行段落分句。
                Sentence sentence = new Sentence();
                sentence.setIndex(i + 1);
                //分句,防止空指针
                if (ObjectUtils.isNotEmpty(NlpSentenceList.get(i).getSentList())) {
                    sentence.setSentences(NlpSentenceList.get(i).getSentList());
                } else {
                    sentence.setSentences(ListUtil.empty());
                }
                //英文使用段落，请求
                if (job.getTtsType().equals("-3")) {
                    sentence.setSentences(ListUtil.toList(NlpSentenceList.get(i).getSent()));
                }

                sentence.setISTitle(Boolean.FALSE);
                //内容图片
                if (ObjectUtils.isEmpty(job.getBackup4())) {
                    sentence.setImages(ListUtil.toList("http://172.16.160.54/text2video/news/default-news-picture.jpg"));
                } else {
                    sentence.setImages(ListUtil.toList(job.getBackup4().replace("\"", "").split(",")));
                }
                sentences.add(sentence);
            }
            return sentences;
        }

        Sentence sentenceTile = new Sentence();
        sentenceTile.setIndex(1);
        sentenceTile.setSentences(ListUtil.toList(jsonObject.getString("title")));
        //标题图片
        if (ObjectUtils.isEmpty(job.getBackup4())) {
            logger.info("没有默认图片:{}", JSONUtil.parseObj(job).toString());
            sentenceTile.setFirstImgId(ListUtil.toList("http://172.16.160.54/text2video/news/default-news-picture.jpg"));
        } else {
            sentenceTile.setFirstImgId(ListUtil.toList(job.getBackup4().replace("\"", "").split(",")[0]));
        }

        sentences.add(sentenceTile);


        for (int i = 0; i < NlpSentenceList.size(); i++) {
            //执行段落分句。
            Sentence sentence = new Sentence();
            sentence.setIndex(i + 2);
            //分句,防止空指针
            if (ObjectUtils.isNotEmpty(NlpSentenceList.get(i).getSentList())) {
                sentence.setSentences(NlpSentenceList.get(i).getSentList());
            } else {
                sentence.setSentences(ListUtil.empty());
            }
            //英文使用段落，请求
            if (job.getTtsType().equals("-3")) {
                sentence.setSentences(ListUtil.toList(NlpSentenceList.get(i).getSent()));
            }

            sentence.setISTitle(Boolean.FALSE);
            //内容图片
            if (ObjectUtils.isEmpty(job.getBackup4())) {
                sentence.setImages(ListUtil.toList("http://172.16.160.54/text2video/news/default-news-picture.jpg"));
            } else {
                sentence.setImages(ListUtil.toList(job.getBackup4().replace("\"", "").split(",")));
            }


            sentences.add(sentence);
        }
        return sentences;
    }

    /**
     * 资源筛选规则
     * 1，合成服务。
     *
     * @param jsonObject nlp结果集
     * @return ArrayList<Sentence> 任务对象
     * @Author: scl
     * @Date: 2021/7/8 14:05
     */
    private ArrayList<Sentence> reComputeResult(JSONObject jsonObject) {

        if (ObjectUtils.isEmpty(jsonObject)) {
            return null;
        }
        JSONArray data = jsonObject.getJSONArray("data");
        List<NlpSentence> NlpSentenceList = JSONUtil.toList(JSONUtil.parseArray(data.toJSONString()), NlpSentence.class);
        List<NlpSentence> indexList = new ArrayList<>();
        JSONArray topic = jsonObject.getJSONArray("topic");
        Iterator<Object> iterator = topic.stream().iterator();
        NlpSentence titleNlpSentence = new NlpSentence();
        while (iterator.hasNext()) {
            JSONObject topic0 = (JSONObject) iterator.next();
            if (topic0.getJSONArray("imgId").size() == 0) {
                continue;
            }
            String name = topic0.getString("name");
            String imgId = (String) topic0.getJSONArray("imgId").get(0);
            titleNlpSentence.setFirstImgId(ListUtil.toList(imgId));
            titleNlpSentence.setKeywords(ListUtil.toList(name));
            titleNlpSentence.setSent(jsonObject.getString("title"));
            break;
        }
        ArrayList<Sentence> sentences = new ArrayList<>();
        //标题放在第一个。并且找到标题图片。
        indexList.add(titleNlpSentence);
        indexList.addAll(NlpSentenceList);
        for (int i = 0; i < indexList.size(); i++) {
            //执行段落分句。
            sentences.add(transformNLPtoComposeVideo(i + 1, indexList.get(i), (i == 0) ? true : false));
        }

        return sentences;
    }

    /**
     * @descp: 格式转换
     * @param:
     * @Author: scl
     * @Date: 2021/9/3 10:42
     */
    private Sentence transformNLPtoComposeVideo(int index, NlpSentence nlp, Boolean bool) {
        Sentence sentence = new Sentence();

        //1，放视频
        if (ObjectUtils.isNotEmpty(nlp.getVideoId())) {
            List<String> videos = new ArrayList<>();
            List<Double> videoDurations = new ArrayList<>();
            nlp.getVideoId().forEach(video -> {
                videos.add(video.getUrl());
                videoDurations.add(video.getDuration());
            });
            sentence.setVideos(videos);
            sentence.setVideoDurations(videoDurations);
        }
        //2,图片
        if (ObjectUtils.isNotEmpty(nlp.getFirstImgId())) {
            sentence.setFirstImgId(nlp.getFirstImgId());
        }
        //3,索引
        sentence.setIndex(index);
        //4，分句,防止空指针
        if (ObjectUtils.isNotEmpty(nlp.getSentList())) {
            sentence.setSentences(nlp.getSentList());
        } else {
            sentence.setSentences(ListUtil.empty());
        }

        if (bool) {
            sentence.setSentences(ListUtil.toList(nlp.getSent()));
        }
        //5,关键字
        sentence.setKeywords(nlp.getKeywords());
        //6，标题
        sentence.setISTitle(bool);
        return sentence;
    }

    /**
     * 记录NLP任务，初始化nlp任务。
     *
     * @param job job信息
     * @return 任务对象
     * @throws Exception
     */
    private Text2videoNlpTask initText2videoNlpTask(Text2videoJob job) {
        Text2videoNlpTask text2videoNlpTask = new Text2videoNlpTask();
        text2videoNlpTask.setNlpId(GeneratID.getNLPGeneratID());
        text2videoNlpTask.setJobId(job.getJobId());
        text2videoNlpTask.setIsSuccess(Enums.JobSign.RUNNING.getKey());
        text2videoNlpTask.setCreateTime(new Date());
        text2videoNlpTask.setCreateBy(job.getCreateBy());
        NlpTaskService.insertText2videoNlpTask(text2videoNlpTask);
        //保证只有单个任务，才更新每个环境状态，减少update
        if (ObjectUtils.isEmpty(job.getZipId())) {
            job.setIsSuccess(Enums.JobSign.RUN_NLP.getKey());
            text2videoJobService.updateText2videoJob(job);
        }
        return text2videoNlpTask;
    }

    private void startComposeVideo(ArrayList<Sentence> sentenceList, Text2videoJob job) throws InterruptedException {
        //替换摘要内容
        String contentAbstract = "";
        for (Sentence sen : sentenceList) {
            for (String sentence : sen.getSentences()) {
                contentAbstract = contentAbstract + " " + sentence;
            }
        }
        job.setContent(contentAbstract);
        //考虑任务TTS任务重试次数，3600秒强制退出。
        int count = Enums.numSign.zero.getKey();
        while (true) {
            // 查询当前的TTS任务集合，执行完。
            int runCount = text2videoTtsTaskMapper.stateTTSRunningStatus(job);
            if (runCount == Integer.parseInt(job.getSentenceSize())) {
                //TTS消耗时间
                /*job.setTtsTime(count);
                job.setIsSuccess(Enums.JobSign.QUEUED_COM.getKey());
                text2videoJobService.updateText2videoJob(job);*/
                break;
            }
            if (count == Enums.numSign.TTSTimeOut.getKey()) {
                job.setEndTime(DateUtils.getNowDate());
                job.setIsSuccess(Enums.JobSign.TTS_FAILED.getKey());
                job.setBackup2(Enums.httpCode.ERROR_19.getValue() + runCount + "/" + job.getSentenceSize());
                text2videoJobService.updateText2videoJob(job);
                return;//主动结束当前线程
            }
            count++;
            Thread.sleep(Enums.numSign.TTSSleepTime.getKey());
        }

        //触发合成任务，异步任务。
        boolean isNewsJob = (ObjectUtils.isNotEmpty(job.getTtsType()) && (job.getTtsType().equals("-1") || job.getTtsType().equals("-3")));
        if (isNewsJob) {
            videoComposeService.videoComposeNews(sentenceList, job);
        } else {
            videoComposeService.videoCompose(sentenceList, job);
        }


    }

    private String requestNLPParams(Text2videoJob job) {
        NlpRequest nlpVO = new NlpRequest();
        nlpVO.setTitle(job.getTitle());
        nlpVO.setText(ListUtil.toList(job.getContent()));

        if (ObjectUtils.isEmpty(job.getTtsType())) {
            nlpVO.setDomain(nlpDomain);
        } else {
            nlpVO.setDomain(Integer.parseInt(job.getTtsType()));
        }
        nlpVO.setModel(nlpModel);
        nlpVO.setThreshold(nlpThreshold);
        nlpVO.setWordsNum(nlpWordsNum);

        //如果是知乎日报，则不调用摘要
        //"backup": {"is_summary": 1} //需要摘要
        //"backup": {"is_summary": 0} //不需要摘要
        NLPBackup backup = new NLPBackup();
        backup.setIs_summary(0);
        nlpVO.setBackup(backup);
/*        if (ObjectUtils.isNotEmpty(job.getBackupText()) && job.getBackupText().contains("知乎")) {
            NLPBackup backup = new NLPBackup();
            backup.setIs_summary(0);
            nlpVO.setBackup(backup);
        } else {
            NLPBackup backup = new NLPBackup();
            backup.setIs_summary(1);
            nlpVO.setBackup(backup);
        }*/
        //logger.info("nlp服务请求参数：{}", JSONUtil.parse(nlpVO).toString());
        return JSONUtil.parse(nlpVO).toString();
    }

    /**
     * @descp: 调用NLP服务
     * @param:
     * @Author: scl
     * @Date: 2021/9/3 10:39
     */
    private JSONObject getGuijiNLPService(Text2videoJob job, Text2videoNlpTask nlptask) {

        Response response;
        JSONObject jsonObject = null;
        RequestBody body = RequestBody.create(MediaType.parse(charset), requestNLPParams(job));
        Request request = new Request.Builder().url(NLU_NEW_URL).post(body).build();
        OkHttpClient okClient = new OkHttpClient.Builder().connectTimeout(Enums.numSign.NLPTimeOut.getKey(), TimeUnit.SECONDS).readTimeout(Enums.numSign.NLPReadTimeOut.getKey(), TimeUnit.SECONDS).build();
        try {
            response = okClient.newCall(request).execute();
            if (response.isSuccessful()) {
                jsonObject = JSON.parseObject(response.body().string());
                Integer status = jsonObject.getInteger("status");
                if (status != 1) {
                    extracted(nlptask, Enums.httpCode.ERROR_05.getValue() + ",status:" + status);
                    return null;
                }
                nlptask.setIsSuccess(Enums.JobSign.SUCCESS.getKey());
                nlptask.setEndTime(new Date());
                //jsonObject存在编码问题，待定。
                nlptask.setResponseResult(JSONObject.toJSONString(jsonObject));
                NlpTaskService.updateText2videoNlpTask(nlptask);
            } else {
                extracted(nlptask, Enums.httpCode.ERROR_06.getValue());
                return null;
            }
        } catch (IOException e) {
            //记录任务SQL状态
            nlptask.setIsSuccess(Enums.JobSign.NLP_FAILED.getKey());
            if (e.toString().length() > Enums.numSign.len256.getKey()) {
                nlptask.setBackup1(e.toString().substring(Enums.numSign.zero.getKey(), Enums.numSign.len256.getKey() - Enums.numSign.one.getKey()));
            } else {
                nlptask.setBackup1(e.toString());
            }
            extracted(nlptask, nlptask.getBackup1());
            logger.error("getGuijiNLPService function error:", e);
            return null;
        }
        jsonObject.put("title", job.getTitle());
        return jsonObject;
    }

    /**
     * @descp: 更新nlp状态，更新Job状态
     * @param: nlptask message
     * @Author: scl
     * @Date: 2021/7/8 14:42
     */
    private void extracted(Text2videoNlpTask nlptask, String message) {
        nlptask.setIsSuccess(Enums.JobSign.NLP_FAILED.getKey());
        nlptask.setEndTime(new Date());
        nlptask.setBackup1(message);
        NlpTaskService.updateText2videoNlpTask(nlptask);
        Text2videoJob job = new Text2videoJob();
        job.setJobId(nlptask.getJobId());
        job.setIsSuccess(Enums.JobSign.NLP_FAILED.getKey());
        job.setEndTime(new Date());
        job.setBackup2(message);
        text2videoJobService.updateText2videoJob(job);
    }
}
